#!/usr/bin/env python3.7.9
'''
Copyright © 2021 DUE TUL
@ date  : Monday january 12, 2020
@ desc  : This modules is used to receive, preprocess and predict the real-time data
@ author:
'''
import time
import random
import requests
import librosa
import numpy as np
import tensorflow as tf
import json
from matplotlib import pyplot as plt

import torch
from gevent import pywsgi
from pandas import DataFrame
from flask import Flask, request

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
rawaudio_dir = 'dataset/raws/'  # date path
tf.compat.v1.enable_eager_execution()
model = tf.keras.models.load_model(r'C:\Users\57222\Desktop\sensor\models\demo-new-merge-cnn130214.h5', compile=False)
# communicate with phone
@app.route('/', methods=["POST"])
def hello():
    if request.method == 'POST':
        a = request.get_data()
        dict1 = json.loads(a)
        data = dict1['data']
        _data = np.array(data).reshape((128, 214))
        plt.imshow(_data, cmap='Blues', aspect='auto', origin='lower', extent=[0, 3, 0, 500], vmin=0)
        plt.show()
        data = np.array(data).reshape((-1, 128, 214, 1))
        result = model.predict(data)
        lab = tf.math.argmax(result, 1)
        lab = tf.keras.backend.eval(lab)
        json_r = ['{:.2f}'.format(i) for i in result[0].tolist()]
        action = ''
        if lab == 0:
            action = 'close'
        elif lab == 1:
            action = 'moving'
        elif lab == 2:
            action = 'open'
        elif lab == 3:
            action = 'rotation'
        json_result = {'action': action, 'result': json_r}
        print(json_result)
        return json_result
    else:
        result_all = "{" + '"action"' + ':' + '"unknow"' + ', ' + '"direction"' + ':' + '"unknow"' + ', ' + '"light"' + ':' + '"unknow"' + "}"
        print(result_all, end=" ")
        return result_all



# magnetometer process function
def magne_process(data):
    direction = 'unknow'
    data = data.replace('[', '').replace(']', '')
    data = data.split(';')[:-1]
    data = DataFrame(data, columns=['Mags'])
    data[['x-axis', 'y-axis', 'z-axis', 'timestamp']] = data['Mags'].str.split(',', expand=True)
    data = data.drop(columns=['Mags'])
    data = data[::3]
    magdata = data
    magdata_x = magdata['x-axis'].astype(float).reset_index(drop=True)
    magdata_y = magdata['y-axis'].astype(float).reset_index(drop=True)
    magdata_z = magdata['z-axis'].astype(float).reset_index(drop=True)
    if abs(magdata_x[1] - magdata_x[35]) < 2:
        if abs(magdata_y[1] - magdata_y[35]) < 2:
            if abs(magdata_z[1] - magdata_z[35]) < 2:
                print('direction: %-6s,   ' % 'unknow', end=' ')
    else:
        x_result = y_result = z_result = 0
        for i in range(0, 34):
            if (magdata_x[35] - magdata_x[i]) >= 0:
                x_result = x_result + 1
            else:
                x_result = x_result - 1

            if (magdata_y[35] - magdata_y[i]) >= 0:
                y_result = y_result + 1
            else:
                y_result = y_result - 1

            if (magdata_z[35] - magdata_z[i]) >= 0:
                z_result = z_result + 1
            else:
                z_result = z_result - 1
        if x_result > 0:
            if y_result > 0:
                if z_result > 0:
                    direction = 'Left'
                else:
                    direction = 'Down'
        if x_result < 0:
            if y_result < 0:
                if z_result < 0:
                    direction = 'Right'
                else:
                    direction = 'Up'

        print('direction: %-6s,   ' % direction, end=' ')
    return direction


# light process function
def light_process(data):
    light = 'unknow'
    data = data.replace('[', '').replace(']', '')
    data = data.split(',')[:-1]
    data = DataFrame(data, columns=['light'])
    data = data.astype(float)
    average = np.mean(data['light'])
    if average < 400:
        light = 'off'
    else:
        light = 'on'
    print('light: %-3s   ' % light, end=' ')
    return light


# load model
def load_data(data_path):
    wav, sr = librosa.load(data_path, sr=16000)
    intervals = librosa.effects.split(wav, top_db=20)
    wav_output = []
    wav_len = int(16000 * 1)
    for sliced in intervals:
        wav_output.extend(wav[sliced[0]:sliced[1]])

    if len(wav_output) > wav_len:
        l = len(wav_output) - wav_len
        r = random.randint(0, l)
        wav_output = wav_output[r:wav_len + r]
    else:
        wav_output.extend(np.zeros(shape=[wav_len - len(wav_output)], dtype=np.float32))
    wav_output = np.array(wav_output) * 1.85
    ps = librosa.feature.melspectrogram(y=wav_output, sr=sr, hop_length=256).astype(np.float32)
    ps = ps[np.newaxis, ..., np.newaxis]
    return ps


# main funciton
if __name__ == "__main__":

    app.run(host='0.0.0.0',port=5000)
